import pygame
import sys
import threading
from queue import Queue
import os

# 初始化pygame
pygame.init()

# 常量定义
GRID_SIZE = 60
GRID_COUNT = 4
SCREEN_SIZE = GRID_SIZE * GRID_COUNT
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 方向定义 (0: 上, 1: 右, 2: 下, 3: 左)
DIRECTIONS = ["上", "右", "下", "左"]

class DogGame:
    def __init__(self):
        self.screen = pygame.display.set_mode((SCREEN_SIZE, SCREEN_SIZE))
        pygame.display.set_caption("儿童编程工具 - 机器人移动")
        self.clock = pygame.time.Clock()
        
        # macOS系统字体设置
        self._init_fonts_for_macos()
        
        # 小狗初始位置和方向
        self.dog_x = 0
        self.dog_y = 0
        self.direction = 1  # 初始向右
        
        # 加载小狗图片
        try:
            script_dir = os.path.dirname(os.path.realpath(__file__))
            dog_image_path = os.path.join(script_dir, "man.jpeg")
            original_img = pygame.image.load(dog_image_path)
            self.original_img = pygame.transform.scale(
                original_img, 
                (GRID_SIZE-10, GRID_SIZE-10)
            )
        except:
            print("无法加载dog.png，将使用红色方块代替")
            self.original_img = pygame.Surface((GRID_SIZE-10, GRID_SIZE-10))
            self.original_img.fill(RED)
        
        # 旋转后的图片缓存
        self.rotated_imgs = [
            pygame.transform.rotate(self.original_img, 90),   # 上
            pygame.transform.rotate(self.original_img, 0),    # 右
            pygame.transform.rotate(self.original_img, 270),  # 下
            pygame.transform.rotate(self.original_img, 180)   # 左
        ]
        
        # 指令队列
        self.command_queue = Queue()
        self.running = True
        self.failed = False
        self.failed_message = "失败！小狗不能走出网格！"
        self.failed_time = 0
    
    def _init_fonts_for_macos(self):
        """专门为macOS初始化字体"""
        # macOS常见中文字体路径
        mac_font_paths = [
            "/System/Library/Fonts/PingFang.ttc",  # 苹方字体
            "/System/Library/Fonts/STHeiti Medium.ttc",  # 华文黑体
            "/System/Library/Fonts/Supplemental/Songti.ttc",  # 宋体
        ]
        
        # 尝试加载macOS系统字体
        self.font = None
        self.fail_font = None
        
        for font_path in mac_font_paths:
            if os.path.exists(font_path):
                try:
                    self.font = pygame.font.Font(font_path, 12)
                    self.fail_font = pygame.font.Font(font_path, 36)
                    print(f"成功加载字体: {font_path}")
                    break
                except:
                    continue
        
        # 如果系统字体加载失败，尝试使用内置字体
        if self.font is None:
            print("无法加载系统字体，尝试使用默认字体")
            try:
                self.font = pygame.font.SysFont("Arial Unicode MS", 24)
                self.fail_font = pygame.font.SysFont("Arial Unicode MS", 36)
            except:
                self.font = pygame.font.SysFont(None, 24)
                self.fail_font = pygame.font.SysFont(None, 36)
                print("警告：无法加载中文字体，中文显示可能不正常")
    
    def process_command(self, command):
        """处理控制台命令"""
        command = command.strip().lower()
        
        if command == "前进":
            self.move_forward()
        elif command == "向右转":
            self.turn_right()
        elif command == "向左转":
            self.turn_left()
        elif command == "向后转":
            self.turn_back()
        elif command == "退出":
            self.running = False
        else:
            print("未知指令，可用指令：前进、向右转、向左转、向后转、退出")
    
    def move_forward(self):
        """小狗前进一格，如果无法前进则显示失败"""
        new_x, new_y = self.dog_x, self.dog_y
        
        if self.direction == 0:  # 上
            new_y -= 1
        elif self.direction == 1:  # 右
            new_x += 1
        elif self.direction == 2:  # 下
            new_y += 1
        elif self.direction == 3:  # 左
            new_x -= 1
        
        # 检查是否超出边界
        if 0 <= new_x < GRID_COUNT and 0 <= new_y < GRID_COUNT:
            self.dog_x, self.dog_y = new_x, new_y
            self.failed = False
        else:
            self.failed = True
            self.failed_time = pygame.time.get_ticks()
    
    def turn_right(self):
        """小狗向右转"""
        self.direction = (self.direction + 1) % 4
    
    def turn_left(self):
        """小狗向左转"""
        self.direction = (self.direction - 1) % 4
    
    def turn_back(self):
        """小狗向后转"""
        self.direction = (self.direction + 2) % 4
    
    def draw(self):
        """绘制游戏界面"""
        self.screen.fill(WHITE)
        
        # 绘制网格
        for x in range(GRID_COUNT):
            for y in range(GRID_COUNT):
                rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE)
                pygame.draw.rect(self.screen, BLACK, rect, 1)
        
        # 绘制小狗
        dog_rect = pygame.Rect(
            self.dog_x * GRID_SIZE + 5, 
            self.dog_y * GRID_SIZE + 5, 
            GRID_SIZE-10, 
            GRID_SIZE-10
        )
        self.screen.blit(self.rotated_imgs[self.direction], dog_rect.topleft)
        
        # 显示当前方向
        if self.font:
            direction_text = self.font.render(f"方向: {DIRECTIONS[self.direction]}", True, BLACK)
            self.screen.blit(direction_text, (10, 10))
        
        # 显示失败消息（3秒后消失）
        if self.failed and pygame.time.get_ticks() - self.failed_time < 3000:
            if self.fail_font:
                fail_text = self.fail_font.render(self.failed_message, True, RED)
                text_rect = fail_text.get_rect(center=(SCREEN_SIZE//2, SCREEN_SIZE//2))
                pygame.draw.rect(self.screen, WHITE, text_rect.inflate(20, 20))
                pygame.draw.rect(self.screen, RED, text_rect.inflate(20, 20), 2)
                self.screen.blit(fail_text, text_rect)
        else:
            self.failed = False
        
        pygame.display.flip()
    
    def run(self):
        """主游戏循环"""
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
            
            # 处理命令队列中的命令
            while not self.command_queue.empty():
                command = self.command_queue.get()
                self.process_command(command)
            
            self.draw()
            self.clock.tick(30)
        
        pygame.quit()
        sys.exit()

def console_input(game):
    """控制台输入线程函数"""
    print("欢迎使用儿童编程工具！")
    print("可用指令：前进、向右转、向左转、向后转、退出")
    
    while game.running:
        command = input("请输入指令：")
        game.command_queue.put(command)
        
        if command.strip().lower() == "退出":
            break

if __name__ == "__main__":
    game = DogGame()
    
    # 启动控制台输入线程
    input_thread = threading.Thread(target=console_input, args=(game,))
    input_thread.daemon = True
    input_thread.start()
    
    # 启动游戏主循环
    game.run()